﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using FlyHorse.LIMS.Model;
using FlyHorse.LIMS.WinApp.LanguageResource;
using System.Data.Entity;

namespace FlyHorse.LIMS.WinApp.BaseManageForms.StandardSelfForms
{
    public partial class StandardSelfMainForm : DevExpress.XtraEditors.XtraForm
    {
        BLL.StandardRawBll standardSelfBll = new BLL.StandardRawBll();
        BLL.ToolBll toolsBll = new BLL.ToolBll();
        OJCB4Entities db = new OJCB4Entities();
        public StandardSelfMainForm()
        {
            InitializeComponent();
        }
        private void StandardSelfMainForm_Load(object sender, EventArgs e)
        {
            //this.gridView1.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;
            //this.gridView1.OptionsBehavior.Editable = false;
            //this.gridView1.OptionsSelection.EnableAppearanceFocusedCell = false;
            //绑定grid里的样品名称
            var goodsList = toolsBll.GetAllGoodList();
            repositoryItemLookUpEdit1.DataSource = goodsList;

            //绑定 grid里的 检验项目
            var testItemList = toolsBll.GetAllTestItemList();
            repositoryItemLookUpEdit2.DataSource = testItemList;

            InitGrid();
        }

        private void InitGrid()
        {
            var models = db.StandardRaws.Where(m => true).OrderBy(m => m.Good.GoodsName).ThenBy(m => m.FormOrder).ToList();
            this.gridControl1.DataSource = models;
        }

        private void ButtonItem_add_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            StandardSelfAddForm standardSelfAddForm = new StandardSelfAddForm(InitGrid);
            standardSelfAddForm.ShowDialog();
        }
        private bool AddStandardSelf(StandardRaw standardSelf)
        {
            //判重复
            int count = standardSelfBll.LoadEntities(m => m.TestItemID == standardSelf.TestItemID && m.GoodsID == standardSelf.GoodsID).Count();
            if (count > 0)
            {
                XtraMessageBox.Show(ResourceOverall.DataExists);
                return false;
            }

            var res = standardSelfBll.AddEntity(standardSelf);
            if (res != null)
            {
                InitGrid();
                XtraMessageBox.Show(ResourceOverall.CreateSucceed);
                return true;
            }
            else
            {
                XtraMessageBox.Show(ResourceOverall.CreateFailed);
                return false;
            }

        }

        private void ButtonItem_Delete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            int selectCount = gridView1.SelectedRowsCount;
            if (selectCount == 0)
            {
                XtraMessageBox.Show(ResourceOverall.SelectNull);
                return;
            }
            int[] selectRows = gridView1.GetSelectedRows();
            DialogResult result = XtraMessageBox.Show(ResourceOverall.ConfirmDelete, ResourceOverall.SystemWarningStr, MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            if (result == DialogResult.OK)
            {
                object sourse = this.gridControl1.DataSource;
                List<StandardRaw> dataSourse = (List<StandardRaw>)sourse;
                List<StandardRaw> delList = new List<StandardRaw>();
                for (int i = 0; i < selectRows.Length; i++)
                {
                    int row = selectRows[i];
                    int dataRowIndex = this.gridView1.GetDataSourceRowIndex(row);
                    StandardRaw standard = dataSourse[dataRowIndex];
                    delList.Add(standard);
                }
                int resCount = BulkDeleteRawStandard(delList);
                if (resCount > 0)
                {
                    InitGrid();
                    XtraMessageBox.Show(ResourceOverall.DeleteSucceed);
                }
            }
        }

        private void ButtonItem_Edit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string id = Convert.ToString(this.gridView1.GetFocusedRowCellValue("StandardRawID"));
            var StandardSelf = standardSelfBll.LoadEntities(m => m.StandardRawID == id).First();
            StandardSelfAddForm standardSelfAddForm = new StandardSelfAddForm(StandardSelf,InitGrid);
            standardSelfAddForm.ShowDialog();
        }

        

        //private void gridView1_DoubleClick(object sender, EventArgs e)
        //{
        //    //ShowEditForm();
        //}

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            int row = e.RowHandle;
            int dataRowIndex = this.gridView1.GetDataSourceRowIndex(row);
            object sourse = this.gridControl1.DataSource;
            List<StandardRaw> dataSourse = (List<StandardRaw>)sourse;
            StandardRaw standard = dataSourse[dataRowIndex];

            if (!String.IsNullOrEmpty(standard.MinValue))
            {
                try
                {
                    Convert.ToDouble(standard.MinValue);
                }
                catch (Exception ex)
                {
                    standard.MinValue = null;
                    XtraMessageBox.Show(ex.Message);
                    return;
                }
            }

            if (!String.IsNullOrEmpty(standard.MaxValue))
            {
                try
                {
                    Convert.ToDouble(standard.MaxValue);
                }
                catch (Exception ex)
                {
                    standard.MaxValue = null;
                    XtraMessageBox.Show(ex.Message);
                    return;
                }
            }

            if (!String.IsNullOrEmpty(standard.MaxValue) && !String.IsNullOrEmpty(standard.MinValue))
            {
                try
                {
                    if (Convert.ToDouble(standard.MinValue) > Convert.ToDouble(standard.MaxValue))
                    {
                        XtraMessageBox.Show(ResourceOverall.ValueCompareErr);
                        this.gridView1.SetRowCellValue(row, e.Column, null);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show(ex.Message);
                    return;
                }
            }
            db.Entry<StandardRaw>(standard).State = EntityState.Modified;
            db.SaveChanges();
        }

        private void StandardSelfMainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.gridView1.CloseEditor();
        }

        private void ButtonItem_ChangeOrder_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FlyHorse.LIMS.WinApp.OtherForms.SetOrderForm form = new OtherForms.SetOrderForm(ChangeOrder);
            form.ShowDialog();
        }

        private void ChangeOrder(TestItem testItem, int order)
        {
            int count = ChangeOrderBll(testItem, order);
            XtraMessageBox.Show(ResourceOverall.EditSucceed + "(" + count + ")");
            InitGrid();
        }



        /// <summary>
        /// 批量删除原材料标准
        /// </summary>
        /// <param name="standardList"></param>
        /// <returns></returns>
        public int BulkDeleteRawStandard(List<StandardRaw> standardList)
        {

            foreach (var standard in standardList)
            {
                var model = db.StandardRaws.Where(m => m.StandardRawID == standard.StandardRawID).First();
                db.Set<StandardRaw>().Remove(model);
            }
            return db.SaveChanges();

        }


        /// <summary>
        /// 批量修改原材料标准的顺序
        /// </summary>
        /// <param name="testItem"></param>
        /// <param name="order"></param>
        /// <returns></returns>
        public int ChangeOrderBll(TestItem testItem, int order)
        {

            var standardList = db.StandardRaws.Where(m => m.TestItemID == testItem.TestItemID);
            foreach (var standard in standardList)
            {
                standard.FormOrder = order;
            }
            return db.SaveChanges();


        }
    }
}